package cn.middle.remote.handler.decodec;

import java.util.List;

import cn.middle.remote.message.SubscribeSignal;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class SubscribeCodec implements Codec<SubscribeSignal> {
	
	
	//消息ID + 数据
    private int mutableLength = 4 + 4 ;

	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, int beginIndex) throws Exception {
		if(in.readableBytes() < mutableLength) {
			in.readerIndex(beginIndex);
			return ;
		}
		
		int msgLength = in.readInt();
		if(!CodecUtil.checkLength(in, msgLength + 4 , beginIndex)) {
			return ;
		}
		
		String msgId = CodecUtil.context(in, msgLength);
		int dataLength = in.readInt();
		if(!CodecUtil.checkLength(in, dataLength , beginIndex)) {
			return ;
		}
		
		byte[] data = CodecUtil.data(in, dataLength);
		SubscribeSignal signal = new SubscribeSignal();
		signal.setId(msgId);
		signal.setData(data);
		out.add(signal);
		
		
	}

	@Override
	public void encode(ChannelHandlerContext ctx, SubscribeSignal msg, ByteBuf out) throws Exception {
		out.writeBytes(msg.toData());
		
	}

}
